package com.david.IfaceAutoTest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.david.IfaceAutoTest.entity.*;
import com.david.IfaceAutoTest.mapper.*;
import com.david.IfaceAutoTest.service.*;
import com.david.IfaceAutoTest.utils.JsonSchemaUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.Header;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author david
 * @since 2021-12-14
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project>
        implements ProjectService {

    @Resource
    ProjectMapper projectMapper;
    @Resource
    ProjectModelMapper projectModelMapper;
    @Resource
    InterfaceMapper interfaceMapper;
    @Resource
    InterfaceHeaderMapper interfaceHeaderMapper;
    @Resource
    InterfaceQueryMapper interfaceQueryMapper;
    @Resource
    InterfaceBodyMapper interfaceBodyMapper;
    @Resource
    InterfaceEventMapper interfaceEventMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cascadeDelProject(Integer projectId) {

        //查询model
        QueryWrapper<ProjectModel> modelQueryWrapper = new QueryWrapper<>();
        modelQueryWrapper.select("id").eq("project_id", projectId);
        List<ProjectModel> projectModels = projectModelMapper.selectList(modelQueryWrapper);
        for (ProjectModel projectModel : projectModels) {
            //查询接口
            QueryWrapper<Interface> interfaceQueryWrapper = new QueryWrapper<>();
            interfaceQueryWrapper.select("id").eq("model_id", projectModel.getId());
            List<Interface> interfaces = interfaceMapper.selectList(interfaceQueryWrapper);
            for (Interface interfaceObj : interfaces) {
                //查询接口header
                QueryWrapper<InterfaceHeader> interfaceHeaderQueryWrapper = new QueryWrapper<>();
                interfaceHeaderQueryWrapper.select("id").eq("interface_id", interfaceObj.getId());
                //查询接口query
                QueryWrapper<InterfaceQuery> interfaceQueryQueryWrapper = new QueryWrapper<>();
                interfaceQueryQueryWrapper.select("id").eq("interface_id", interfaceObj.getId());
                //查询接口body
                QueryWrapper<InterfaceBody> interfaceBodyQueryWrapper = new QueryWrapper<>();
                interfaceBodyQueryWrapper.select("id").eq("interface_id", interfaceObj.getId());
                //查询接口event
                QueryWrapper<InterfaceEvent> interfaceEventQueryWrapper = new QueryWrapper<>();
                interfaceBodyQueryWrapper.select("id").eq("interface_id", interfaceObj.getId());
                //倒序删除
                interfaceBodyMapper.delete(interfaceBodyQueryWrapper);
                interfaceQueryMapper.delete(interfaceQueryQueryWrapper);
                interfaceHeaderMapper.delete(interfaceHeaderQueryWrapper);
                interfaceEventMapper.delete(interfaceEventQueryWrapper);
            }
            interfaceMapper.delete(interfaceQueryWrapper);
            projectModelMapper.delete(modelQueryWrapper);
        }
        projectMapper.deleteById(projectId);


    }


    @Override
    public Boolean validateFile(MultipartFile multipartFile) throws IOException {
        String fileStr = getFileStr(multipartFile);
        //校验文件格式、层级
        //特定格式模板
        String schemaFilePath = "classpath:jsonSchema/test.json";
        //检查格式
        return JsonSchemaUtil.getProcessingReport(fileStr, schemaFilePath);
    }


    @Override
    @Transactional
    public void upload(MultipartFile file) throws IOException {
        String fileStr = getFileStr(file);
        JSONObject projectJson = JSONObject.fromObject(fileStr);
        JSONObject projectInfoJson = projectJson.getJSONObject("info");
        //项目数据入库
        Project project = new Project();
        project.setProjectName(projectInfoJson.getString("name"));
        projectMapper.insert(project);
        Integer projectId = project.getId();

        //处理item json 数组
        JSONArray projectItemJsonArray = JSONArray.fromObject(projectJson.get("item"));
        for (Object o : projectItemJsonArray) {
            JSONObject modelJson = JSONObject.fromObject(o);
            //模块数据入库
            ProjectModel projectModel = new ProjectModel();
            projectModel.setModelName(modelJson.getString("name"));
            projectModel.setProjectId(projectId);
            projectModel.setModelType(0);
            projectModelMapper.insert(projectModel);

            Integer projectModelId = projectModel.getId();
            JSONArray modelItemJsonArray = modelJson.getJSONArray("item");
            for (Object o1 : modelItemJsonArray) {
                JSONObject interfaceJson = JSONObject.fromObject(o1);
                JSONObject iFaceRequestObject = interfaceJson.getJSONObject("request");
                JSONObject iFaceUrlJsonObject = iFaceRequestObject.getJSONObject("url");

                JSONArray iFaceHeaderArray = iFaceRequestObject.getJSONArray("header");

                //接口数据入库
                Interface anInterface = new Interface();
                anInterface.setModelId(projectModelId);
                anInterface.setInterfaceName(interfaceJson.getString("name"));
                anInterface.setInterfaceMethod(iFaceRequestObject.getString("method"));
                anInterface.setHost(iFaceUrlJsonObject.getString("host"));
                anInterface.setInterfacePath(iFaceUrlJsonObject.getString("path"));
                anInterface.setInterfaceProtocol(iFaceUrlJsonObject.getString("protocol"));
                anInterface.setInterfaceRaw(iFaceUrlJsonObject.getString("raw"));
                interfaceMapper.insert(anInterface);
                System.out.println(anInterface);

                for (Object o2 : iFaceHeaderArray) {
                    JSONObject iFaceHeaderJson = JSONObject.fromObject(o2);
                    InterfaceHeader interfaceHeader = new InterfaceHeader();
                    interfaceHeader.setInterfaceId(anInterface.getId());
                    interfaceHeader.setHeaderKey(iFaceHeaderJson.getString("key"));
                    interfaceHeader.setHeaderValue(iFaceHeaderJson.getString("value"));
                    interfaceHeader.setHeaderType(iFaceHeaderJson.getString("type"));
                    interfaceHeaderMapper.insert(interfaceHeader);
                }
                if (iFaceUrlJsonObject.has("query") && iFaceRequestObject.getString("method").equalsIgnoreCase("GET")) {
                    JSONArray iFaceQueryJsonArray = iFaceUrlJsonObject.getJSONArray("query");
                    for (Object o2 : iFaceQueryJsonArray) {
                        InterfaceQuery interfaceQuery = new InterfaceQuery();
                        JSONObject iFaceQueryJson = JSONObject.fromObject(o2);
                        interfaceQuery.setInterfaceId(anInterface.getId());
                        interfaceQuery.setQueryKey(iFaceQueryJson.getString("key"));
                        interfaceQuery.setQueryValue(iFaceQueryJson.getString("value"));
                        interfaceQueryMapper.insert(interfaceQuery);
                    }
                }

                if (iFaceRequestObject.getString("method").equalsIgnoreCase("POST")) {
                    JSONObject iFaceBodyObject = iFaceRequestObject.getJSONObject("body");
                    InterfaceBody interfaceBody = new InterfaceBody();
                    interfaceBody.setInterfaceId(anInterface.getId());
                    interfaceBody.setBodyMode(iFaceBodyObject.getString("mode"));
                    interfaceBody.setModeValue(iFaceBodyObject.getString("raw"));
                    interfaceBody.setBodyOptions(iFaceBodyObject.getString("options"));
                    interfaceBodyMapper.insert(interfaceBody);
                }

                if (interfaceJson.has("event")) {
                    JSONArray eventArray = interfaceJson.getJSONArray("event");
                    if (eventArray.size() > 0) {

                        System.out.println(eventArray);
                        for (Object o2 : eventArray) {

                            InterfaceEvent interfaceEvent = new InterfaceEvent();
                            JSONObject eventObject = JSONObject.fromObject(o2);
                            interfaceEvent.setInterfaceId(anInterface.getId());
                            interfaceEvent.setListen(eventObject.getString("listen"));
                            interfaceEvent.setScript(eventObject.getString("script"));
                            interfaceEventMapper.insert(interfaceEvent);
                        }
                    }
                }
            }
        }

        //TODO 处理依赖变量（query 、header、body 中依赖其他接口的变量添加依赖键，设置依赖项。 ）
    }


    private String getFileStr(MultipartFile multipartFile) throws IOException {
        InputStream stream = multipartFile.getInputStream();
        InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        while (bufferedReader.ready()) {
            stringBuilder.append(bufferedReader.readLine());
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }
}
